import { createRouter, createWebHashHistory } from 'vue-router'
import Login from "../views/Login.vue"  
import MainBox from "../views/MainBox.vue"  
import RoutesConfig from './config'
import store from '../store/index' //导入vuex
// 路由的路径
const routes = [
  {
    path:"/login",
    name:"login",
    component:Login
  },
  {
    path:"/mainbox",
    name:"mainbox",
    component:MainBox
  }
  //mainbox动态路由根据后面权限动态添加

]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})


//每次路由跳转之前 （路由拦截）
router.beforeEach((to,from,next)=>{
  // console.log(to.name)
  if(to.name==="login"){ //如果当前路径是login 就放行
    next()
  }else{
    //如果授权（以及登陆过了）next()
    //未授权,重定向到login
    if(!localStorage.getItem("token")){//获取本地存储token
      next({ //next 拦截之后。。
        path:"/login"  //重定向
      })
    }else{
      
      if(!store.state.isGetterRouter){
        //不能让第二次进来会死循环
        router.removeRoute("mainbox")
        ConfigRouter()
        next({
          path:to.fullPath 
          //这个方法是又会在走一遍这个路径
        })
      }else{
        next()
      }
    }
  }
})
//config里面的子路由
const ConfigRouter = ()=>{
  if(!router.hasRoute("mainbox")){
    router.addRoute({
        path:"/mainbox",
        name:"mainbox",
        component:MainBox
    })
  }

    RoutesConfig.forEach(item =>{
    // router.addRoute("mainbox",item)
    checkPermission(item) && router.addRoute("mainbox",item)
  })
  //改变isGetterRouter = true
  store.commit("changeGetterRouter",true)
}
const checkPermission = (item)=>{
  if(item.requireAdmin){
    return store.state.userInfo.role===1
  }
  return true
}
export default router
